<template>
  <div class="editConfig">
    <Form :model="modelForm" ref="modelForm" :rules="rule">
      <Row>
        <Col :span="11">
          <Form-Item prop="taskYear" label="填报周期：" :label-width="110">
            <Select v-model="modelForm.taskYear" placeholder="请选择年度">
              <Option v-for="item2 in yearList" :key="item2.key" :value="item2.value">{{item2.value}}</Option>
            </Select>
          </Form-Item>
        </Col>
        <Col :span="2" style="text-align: center; padding-top:5px">
        --
        </Col>
        <Col :span="11">
          <Form-Item prop="taskQuarter" label="">
            <Select v-model="modelForm.taskQuarter" placeholder="请选择季度">
              <Option v-for="item2 in datasList" :key="item2.key" :value="item2.value">{{item2.value}}</Option>
            </Select>
          </Form-Item>
        </Col>
      </Row>
    </Form>
  </div>
</template>

<script>
import sysConfigApi from '@/api/sysConfig.js'
import coverApi from '@/api/cover';
export default {
  name: 'editConfig',
  props: {
    type: {
      typeof: String
    },
    reportName: {
      typeof: String
    },
    title: {
      typeof: String
    },
    year: {
      typeof: String
    },
    quarter: {
      typeof: String
    }
  },
  data() {
    return {
      timer: null,
      taskId: '',
      yearList: [
        {key:'2021',value:'2021'},
        {key:'2022',value:'2022'},
        {key:'2023',value:'2023'},
        {key:'2024',value:'2024'},
        {key:'2025',value:'2025'},
      ],
      datasList:[
        {key:'0',value:'1'},
        {key:'1',value:'2'},
        {key:'2',value:'3'},
        {key:'3',value:'4'},
      ],
      modelForm: {
        taskYear: '',
        taskQuarter: ''
      },
      rule: {
        taskYear: [{required: true, message: "请选择填报年度", trigger: "change"}],
        taskQuarter: [{required: true, message: "请选择填报季度", trigger: "change"}]
      },
    }
  },
  computed: {
    contentMap() {
      const contentList = {
        auto: '您即将对任务项进行自动更新，此操作不可撤回，您要继续吗？',
        cover: `您将设置填报季度为${this.modelForm.taskYear}-Q${this.modelForm.taskQuarter}`,
        count: `您即将生成${this.modelForm.taskYear}-${this.modelForm.taskQuarter}季度统计报表，生成后无法撤回，您要继续吗？`,
        coverCount: `您将设置统计报表季度为${this.modelForm.taskYear}-Q${this.modelForm.taskQuarter}`
      }
      return contentList[this.type]
    }
  },
  created() {
    this.modelForm = {
      taskYear: this.year ? this.year : '',
      taskQuarter: this.quarter ? this.quarter : '',
    },
    this.$emit("SetTitle", this.title);
    this.$emit("SetPageWidth", 600);
    this.$emit("SetPageMinHeight", 100);
    this.$emit("SetScroll", 'inherit');
    this.$emit("SetPageActions", [
      {
        text: '确定',
        theme: "primary",
        action: "submit",
        handle: () => {
          this.$refs['modelForm'].validate(valid => {
            if (valid && !this.timer) {
              this.$confirm({
                title:"",
                content: this.contentMap
              }).then(async ()=>{
                this.$emit("SetActionsState", {
                  btn: "submit",
                  state: true
                })
                if (this.type === 'coverCount') {
                  // 覆盖度统计配置，没有接口，临时写死为更新成功
                  this.$Message.success({
                    content: '更新成功',
                    duration: 3
                  })
                  this.$emit("Close", this.modelForm)
                  return
                }
                this.submit().then(res => {
                  console.log("type", this.type)
                  if (res.data.code === 200 || res.status == 200) {
                    if (this.type === 'auto') {
                      this.taskId = res.data.data
                      this.startTimer()
                      return
                    } 
                    if (this.type === 'cover'){
                      this.$store.dispatch('getBuList')
                    }
                    // 修复覆盖度填报配置接口成功没有响应data
                    this.$Message.success({
                      content: res.data.data === true || this.type === 'cover' ? '更新成功' : res.data.data,
                      duration: 3
                    })
                    this.$emit("SetActionsState", {
                      btn: "submit",
                      state: false
                    });
                    this.$emit("Close", true);
                  } else {
                      this.$emit("SetActionsState", {
                        btn: "submit",
                        state: false
                      });
                      this.$Message.error({
                        content: res.data.msg || '更新失败',
                        duration: 3
                      })
                    }
                  }).catch(err => {
                    this.$Message.error({
                      content: err || '更新失败',
                      duration: 3
                    })
                    this.$emit("SetActionsState", {
                      btn: "submit",
                      state: false
                    });
                  })
              })
            }
          })
        }
      },
      {
        text: '取消',
        theme: "primary",
        handle: () => {
          this.$emit("Close");
        }
      },
    ]);
  },
  beforeDestroy() {
    clearInterval(this.timer)
    this.timer = null
  },
  methods: {
    startTimer(id){
      this.timer = setInterval(this.queryAutoRefreshSubmitStatus, 2000); // 注意: 第一个参数为方法名的时候不要加括号;
    },
    endTimer() {
      clearInterval(this.timer)
      this.timer = null
    },
    updateWriteable(description, targetDate) {
      description.forEach(item => {
        if (item.value === targetDate) {
          item['writeable'] = true
        } else {
          if (item.hasOwnProperty('writeable')) {
            delete item['writeable']
          }
        }
      })
      return description
    },
    async coverSubmit() {
      const res = await coverApi.getCodeList('BU')
      const quarterList = res.data.records.filter(item => item.vsiKey === 'BU_TIME_LIST')[0]
      const description = JSON.parse(quarterList.vsiDescription)
      const targetDate = this.modelForm.taskYear + '-Q' + this.modelForm.taskQuarter
      const newDescription = this.updateWriteable(description, targetDate)
      const valueSetItemLangVos = await coverApi.getLangVos(quarterList.id)
      let params = {
        id: quarterList.id,
        vsCode: quarterList.vsCode,
        vsiKey: quarterList.vsiKey,
        valueSetItemLangVos: valueSetItemLangVos,
        vsiDescription: JSON.stringify(newDescription)
      }
      return coverApi.updateCodeList(params)
    },
    submit() {
      if (this.type === 'auto') {
        const params = {reportName: this.reportName, ...this.modelForm}
        return sysConfigApi.autoRefreshSubmit(params)
      } else if (this.type === 'count') {
        const params = {reportName: this.reportName, ...this.modelForm}
        return sysConfigApi.countSubmit(params)
      } else if (this.type === 'cover') {
        return this.coverSubmit()
      } else {
        return 
      }
    },
    queryAutoRefreshSubmitStatus() {
      sysConfigApi.queryAutoRefreshSubmitStatus({id: this.taskId}).then(res => {
        if (res.data.code === 200) {
          if (res.data.data != '0') {
            this.$Message.success({
              content: res.data.data || '更新成功',
              duration: 3
            })
            this.endTimer()
            this.$emit("SetActionsState", {
              btn: "submit",
              state: false
            });
            this.$emit("Close", true);
          }
        } else {
          this.endTimer()
          this.$Message.error({
            content: res.data.msg || '更新失败',
            duration: 3
          })
          this.$emit("SetActionsState", {
            btn: "submit",
            state: false
          });
        }
      }).catch(err => {
        this.$Message.error({
          content: err || '更新失败',
          duration: 3
        })
        this.endTimer()
        this.$emit("SetActionsState", {
          btn: "submit",
          state: false
        });
      })
    }
  }
}
</script>

<style lang="less" scoped>
.editConfig {
  height: 100%;
}
</style>
